/**
 * @author thaodo
 *
 *
 */
package com.mfsoft.fragment;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.Util;
import com.mfsoft.adapter.GridViewAdapter;
import com.mfsoft.camera.OpenImageActivity;
import com.mfsoft.camera.R;
import com.mfsoft.model.ImageItem;
import com.mfsoft.model.JSONParser;
import com.mfsoft.utilities.Config;
import com.mfsoft.utilities.Utils;
import com.mfsoft.utilities.Variables;

public class ImageServerFragment extends Fragment implements
		OnItemClickListener {
	private GridView gridPhotos;
	private GridViewAdapter adapter;
	private int columnWidth;
	private Utils utils;
	private TextView tvNoImage;
	private ProgressBar pbgLoadMore;
	boolean loadingMore = false;
	boolean stopLoadMore = false;
	int userId = 22;
	int curPage = 1;
	// long loadStart;

	// private static final String LOG_NETWORK = "CheckNetworkStatus";
	private NetworkChangeReceiver receiver;
	private boolean isConnected = false;

	AlertDialog alert;
	public static final int SETTINGS = 0;

	LoadMoreServerTask loadMore;

	// private AlertDialog.Builder openNetwork;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.grid_view, container, false);
		initAlertNetworkSetting();
		utils = new Utils(getActivity());

		registerReceiver();

		gridPhotos = (GridView) v.findViewById(R.id.gvAlbum);
		tvNoImage = (TextView) v.findViewById(R.id.tvNoImage);

		initGridLayout();
		adapter = new GridViewAdapter(getActivity(), R.drawable.loader,
				Variables.imagesServer, columnWidth);

		if (Variables.imagesServer.size() == 0) {
			tvNoImage.setVisibility(View.VISIBLE);
		} else {
			tvNoImage.setVisibility(View.GONE);
			// openNetworkSetting();
		}

		gridPhotos.setAdapter(adapter);
		gridPhotos.setOnItemClickListener(this);
		pbgLoadMore = (ProgressBar) v.findViewById(R.id.pgbLoadMore);
		// load more
		gridPhotos.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				int lastInScreen = firstVisibleItem + visibleItemCount;
				// System.out.println("total: " + totalItemCount + " last: "
				// + lastInScreen);
				if ((lastInScreen == totalItemCount) && !loadingMore
						&& (Variables.imagesServer.size() != 0)) {

					if (!stopLoadMore) {
						if (isConnected) {
							curPage += 1;
							// System.out.println("curPage: " + curPage);
							// new LoadMoreServerTask().execute(userId,
							// curPage);

							loadMore = new LoadMoreServerTask();
//							new Thread() {
//								@Override
//								public void run() {
//									try {
//										loadMore.execute(userId, curPage).get(
//												Config.TIMEOUT,
//												TimeUnit.MILLISECONDS);
//									} catch (Exception e) {
//										// TODO: handle exception
//										if (curPage > 1) {
//											curPage -= 1;
//										}
//										loadMore.cancel(true);
//										// pbgLoadMore.setVisibility(View.GONE);
//									}
//								}
//							}.start();

							try {
								loadMore.execute(userId, curPage).get(
										Config.TIMEOUT,
										TimeUnit.MILLISECONDS);
							} catch (Exception e) {
								// TODO: handle exception
								if (curPage > 1) {
									curPage -= 1;
								}
								loadMore.cancel(true);
								// pbgLoadMore.setVisibility(View.GONE);
							}
							
						} else {
							// show thong bao vui long mo ket noi mang
							// Toast.makeText(
							// getActivity(),
							// "Khong co ket noi Internet. Vui long mo ket noi Internet.",
							// Toast.LENGTH_LONG).show();
							// openNetwork.show();
							System.out.println("isConnected: " + isConnected);
							alert.show();
						}
					} else {
						Toast.makeText(getActivity(),
								"Da load het anh tu server.", Toast.LENGTH_LONG)
								.show();
					}
				}

			}
		});

		// v.setOnKeyListener(this);
		return v;
	}

	public void registerReceiver() {
		IntentFilter filter = new IntentFilter(
				ConnectivityManager.CONNECTIVITY_ACTION);
		receiver = new NetworkChangeReceiver();
		getActivity().registerReceiver(receiver, filter);
	}

	public void unregisterReceiver() {
		getActivity().unregisterReceiver(receiver);
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		unregisterReceiver();
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		registerReceiver();
//		openNetworkSetting();
	}
	
	public void initGridLayout() {
		Resources r = getResources();
		float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
				Variables.GRID_PADDING, r.getDisplayMetrics());

		int diaInch = utils.diaInch();
		System.out.println("inch" + diaInch);
		if (diaInch < 9 && diaInch >= 6.5) {
			// tablet 7: 3 hinh
			padding *= 2;
			columnWidth = (int) (utils.getScreenWidth() - ((Variables.NUM_OF_COLUMNS + 2) * padding)
					/ Variables.NUM_OF_COLUMNS);
			gridPhotos.setNumColumns(Variables.NUM_OF_COLUMNS + 1);
		} else if (diaInch > 9) {
			// tablet 10
			padding *= 2;
			columnWidth = (int) (utils.getScreenWidth() - ((Variables.NUM_OF_COLUMNS + 2) * padding)
					/ Variables.NUM_OF_COLUMNS);
			gridPhotos.setNumColumns(Variables.NUM_OF_COLUMNS + 1);
		} else {
			// fix chieu rong cua hinh
			columnWidth = (int) (utils.getScreenWidth() - ((Variables.NUM_OF_COLUMNS + 1) * padding)
					/ Variables.NUM_OF_COLUMNS);
			gridPhotos.setNumColumns(Variables.NUM_OF_COLUMNS);

		}
		System.out.println("column: " + columnWidth);
		gridPhotos.setColumnWidth(columnWidth);
		// gridPhotos.setStretchMode(GridView.NO_STRETCH);
		gridPhotos.setPadding((int) padding, (int) padding, (int) padding,
				(int) padding);
		gridPhotos.setHorizontalSpacing((int) padding);
		gridPhotos.setVerticalSpacing((int) padding);
	}

	public boolean openNetworkSetting() {
		// System.out.println("isConnected: " + isConnected);
		if (Variables.imagesServer.size() == 0) {
			// chua co anh: ko mo mang Internet, ko load dc du lieu du da co
			// gang ket noi ...
			// tvNoImage.setVisibility(View.VISIBLE);
			if (isConnected) {
				// new LoadMoreServerTask().execute(userId,
				// curPage);
				// set time out cho asynctask
				loadMore = new LoadMoreServerTask();
//				new Thread() {
//					@Override
//					public void run() {
//						try {
//							System.out.println("curPage: " + curPage);
//							loadMore.execute(userId, curPage).get(
//									Config.TIMEOUT, TimeUnit.MILLISECONDS);
//						} catch (Exception e) {
//							// TODO: handle exception
//							System.out.println("cancel load voi page = 1");
//							loadMore.cancel(true);
//							pbgLoadMore.setVisibility(View.GONE);
//							tvNoImage.setVisibility(View.VISIBLE);
//						}
//					}
//				}.start();
				
				
				try {
					System.out.println("curPage: " + curPage);
					loadMore.execute(userId, curPage).get(
							Config.TIMEOUT, TimeUnit.MILLISECONDS);
				} catch (Exception e) {
					// TODO: handle exception
					System.out.println("cancel load voi page = 1");
					loadMore.cancel(true);
					pbgLoadMore.setVisibility(View.GONE);
					tvNoImage.setVisibility(View.VISIBLE);
				}
				
				
//				System.out.println("image server size: "
//						+ Variables.imagesServer.size());
				// break;
				// return true;
			} else {
				// show thong bao vui long mo ket noi mang
				// Toast.makeText(
				// getActivity(),
				// "Khong co ket noi Internet. Vui long mo ket noi Internet.",
				// Toast.LENGTH_LONG).show();
				// openNetwork.show();
				alert.show();
				return false;
			}

		} else {
			if (!isConnected) {
				alert.show();
			}
		}
		return true;
	}

	// mo network setting
	public void initAlertNetworkSetting() {
		AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this.getActivity());
		alertBuilder.setTitle("Network setting");
		alertBuilder.setMessage("Vui long mo ket noi Internet?");

		alertBuilder.setNegativeButton("Cancel", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});

		alertBuilder.setPositiveButton("Settings", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int arg1) {
				// new Handler().postDelayed(new Runnable() {
				//
				// @Override
				// public void run() {
				// Intent i = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
				// // startActivity(i);
				// startActivityForResult(i, SETTINGS);
				// }
				// }, Config.TIMEOUT);
				Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
				// startActivity(i);
				// startActivityForResult(intent, SETTINGS);
				// System.out.println("start result");
				startActivity(intent);
//				getActivity().finish();
			}
		});
		
		alert = alertBuilder.create();

	}

	// @Override
	// public void onResume() {
	// // TODO Auto-generated method stub
	// super.onResume();
	// if (Variables.FRAG == 1) {
	// System.out.println("back");
	// openNetworkSetting();
	// }
	//
	//
	// }

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// getActivity();
		if (requestCode == SETTINGS) {
			loadMore = new LoadMoreServerTask();
			new Thread() {
				@Override
				public void run() {
					try {
						System.out.println("result load");
						loadMore.execute(userId, curPage).get(Config.TIMEOUT,
								TimeUnit.MILLISECONDS);
					} catch (Exception e) {
						System.out.println("result cancel");
						// TODO: handle exception
						loadMore.cancel(true);
						// pbgLoadMore.setVisibility(View.GONE);
					}
				}
			}.start();

			if (Variables.imagesServer.size() == 0) {
				tvNoImage.setVisibility(View.VISIBLE);
			} else {
				tvNoImage.setVisibility(View.GONE);
			}
		}

	}

	// cac tham so gui den server
	public ArrayList<NameValuePair> setPostEntity(int userId, int page) {
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("command", "getmyalbum"));
		params.add(new BasicNameValuePair("userid", String.valueOf(userId)));
		params.add(new BasicNameValuePair("page", String.valueOf(page)));
		return params;
	}

	// kiem tra ket noi internet
	// public boolean isConnected() {
	// ConnectivityManager cm = (ConnectivityManager) getActivity()
	// .getSystemService(Activity.CONNECTIVITY_SERVICE);
	// NetworkInfo networkInfo = cm.getActiveNetworkInfo();
	// if (networkInfo != null && networkInfo.isConnected())
	// return true;
	// else
	// return false;
	// }

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// click vao moi hinh anh thi ....
		Intent intent = getActivity().getIntent();
		// put object image item tuong ung di
		intent.putExtra("image", Variables.imagesServer.get(position));
		// System.out.println("anh: "
		// + Variables.imagesServer.get(position).toString());
		// startActivity(intent);
		getActivity().setResult(Activity.RESULT_OK, intent);
		getActivity().finish();
	}

	// asyntask load more
	class LoadMoreServerTask extends AsyncTask<Integer, Void, Void> {

		@Override
		protected Void doInBackground(Integer... params) {

			loadingMore = true;
			// curPage += 1;

			// TODO Auto-generated method stub
			JSONParser jParser = new JSONParser();
			JSONObject jObject = jParser.getJSONFromUrl(Variables.URL,
					setPostEntity(params[0], params[1]));
			if (jObject == null) {
				stopLoadMore = true;
				this.cancel(true);
				pbgLoadMore.setVisibility(View.GONE);
			} else {

				// lay array result
				try {
					Log.w("debug json", Variables.TAG_RESULT + "");
					// cho nay chac no ko hieu gi result la gi
					JSONArray jArray = jObject
							.getJSONArray(Variables.TAG_RESULT);
					// vong lap lay ra url cua cac image
					for (int i = 0; i < jArray.length(); i++) {
						JSONObject img = jArray.getJSONObject(i);

						Variables.imagesServer.add(new ImageItem(img
								.getString(Variables.TAG_IMAGEURL), img
								.getString(Variables.TAG_NAME), img
								.getString(Variables.TAG_SIZE), img
								.getString(Variables.TAG_DATE), ""));
					}
					// System.out.println("server: " +
					// Variables.imagesServer.size());
				} catch (JSONException e) {
					e.printStackTrace();
					this.cancel(true); // anh fix tam cho nay cho em nha, json
										// tra ve sai (gia tri la -1) thi stop
										// asynctask nay
					pbgLoadMore.setVisibility(View.GONE);
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// vi tri hien tai cua grid view
			int curPosition = gridPhotos.getFirstVisiblePosition();
			adapter = new GridViewAdapter(getActivity(), R.drawable.loader,
					Variables.imagesServer, columnWidth);
			gridPhotos.setAdapter(adapter);
			gridPhotos.setSelection(curPosition);
			loadingMore = false;
			pbgLoadMore.setVisibility(View.GONE);
			tvNoImage.setVisibility(View.GONE);
		}

		@Override
		protected void onPreExecute() {
			// hien thi load bar
			pbgLoadMore.setVisibility(View.VISIBLE);
			if(alert!=null){
				alert.dismiss();
			}
			// loadStart = System.currentTimeMillis();
			// try {
			// Thread.sleep(10000);
			// } catch (InterruptedException e1) {
			// // TODO Auto-generated catch block
			// e1.printStackTrace();
			// }
			super.onPreExecute();
		}

	}

	class NetworkChangeReceiver extends BroadcastReceiver {

		// listen network change
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.v(Variables.LOG_NETWORK,
					"Received notification about network status");
			isNetworkAvailabel(context);

		}

		private boolean isNetworkAvailabel(Context context) {
			ConnectivityManager connectivity = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null) {
				NetworkInfo[] info = connectivity.getAllNetworkInfo();
				if (info != null) {
					for (int i = 0; i < info.length; i++) {
						if (info[i].getState() == NetworkInfo.State.CONNECTED) {
							if (!isConnected) {
								Log.v(Variables.LOG_NETWORK,
										"Now you are connected Internet");
								isConnected = true;
								// muon lam gi thi lam o day
								// post data hoac update tu server ...
//								openNetworkSetting();
								loadMore = new LoadMoreServerTask();
								try {
									loadMore.execute(userId, curPage).get(Config.TIMEOUT * 30,
									TimeUnit.MILLISECONDS);
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (ExecutionException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (TimeoutException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
							return true;
						}

					}
				}
			}
			Log.v(Variables.LOG_NETWORK, "you are not connected Internet");
			isConnected = false;
			return false;
		}

	}

}
